package com.reborn.mall.api.controller;

import com.reborn.mall.api.model.entity.AppUser;
import com.reborn.mall.api.model.vo.LoginInfoVO;
import com.reborn.mall.api.service.AppUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * 认证授权Controller
 *
 * @author wu.yue
 * @since 2020/2/29
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private AppUserService appUserService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @PostMapping("/register")
    public AppUser register(@RequestBody AppUser appUserParam) {
        return appUserService.register(appUserParam);
    }

    @PostMapping("/login")
    public LoginInfoVO login(@RequestBody AppUser appUserParam) {
        String token = appUserService.login(appUserParam.getUsername(), appUserParam.getPassword());
        if (token == null) {
            return LoginInfoVO.failed("用户名或密码错误");
        }
        return LoginInfoVO.success(token, tokenHead);
    }

    @GetMapping
    public AppUser auth() {
        Optional<AppUser> currentUser = appUserService.getCurrentUser();
        return currentUser.map(appUser -> appUserService.getUserByUsername(appUser.getUsername())).orElse(null);
    }

    @GetMapping("/logout")
    public void logout() {
        SecurityContextHolder.clearContext();
    }
}
